<template>
  <div class="dishes-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加菜品
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索菜品"
        style="width: 200px; margin-left: 16px"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 菜品列表 -->
    <el-table :data="dishes" style="width: 100%" v-loading="loading">
      <el-table-column prop="ID" label="ID" width="80" />
      <el-table-column label="图片" width="120">
        <template #default="{ row }">
          <el-image
            :src="row.image_url || '/default-dish.jpg'"
            style="width: 60px; height: 60px"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="菜品名称" />
      <el-table-column prop="price" label="价格">
        <template #default="{ row }">
          <span>¥{{ row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="Category" label="分类" />
      <el-table-column prop="Stock" label="库存" width="100" />
      <el-table-column label="标签" min-width="200">
        <template #default="scope">
          <div class="tag-container">
            <el-tag
              v-for="tag in scope.row.Tags"
              :key="tag"
              :type="getTagType(tag)"
              effect="plain"
              size="small"
              class="tag-item"
            >
              {{ getTagText(tag) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑/添加对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加菜品' : '编辑菜品'"
      width="50%"
      @closed="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="form.price"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="库存" prop="stock">
          <el-input-number 
            v-model="form.stock"
            :min="0"
          />
        </el-form-item>
        
        <el-form-item label="标签">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
            :before-create="handleTagInput"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            rows="3"
          />
        </el-form-item>
        
        <el-form-item label="图片">
          <el-upload
            class="dish-uploader"
            action="http://localhost:8080/api/upload"
            :headers="{ 'Authorization': `Bearer ${store.state.token}` }"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
          >
            <img v-if="form.image_url" :src="form.image_url" class="uploaded-image" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip" v-if="!form.image_url">
            <span>点击上传图片</span>
            <div class="tip-text">支持 jpg、png、gif 格式，大小不超过 2MB</div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

// 定义与后端对应的接口
interface Dish {
  ID: number
  Name: string
  Price: number
  Description: string
  Category: string
  ImageURL: string
  Stock: number
  Status: string
  Tags: string[]
  CreatedAt: string
  UpdatedAt: string
}

const store = useStore()
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const dishes = ref<Dish[]>([])
const formRef = ref<FormInstance>()
const searchQuery = ref('')

// 表单数据
const form = ref({
  name: '',
  price: 0,
  description: '',
  category: '',
  image_url: '',
  stock: 0,
  tags: [] as string[],
  status: 'available'
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
}

// 分类选项
const categories = ['川菜', '粤菜', '湘菜', '东北菜']
const availableTags = ['辣', '酸', '甜', '咸', '招牌', '新品']

// 加载菜品列表
const loadDishes = async () => {
  loading.value = true
  try {
    const response = await fetch(`http://localhost:8080/api/dishes?search=${searchQuery.value}`, {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      dishes.value = data.dishes
    } else {
      ElMessage.error(data.error || '加载菜品列表失败')
    }
  } catch (error) {
    ElMessage.error('加载菜品列表失败')
  } finally {
    loading.value = false
  }
}

// 处理添加
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    price: 0,
    description: '',
    category: '',
    image_url: '',
    stock: 0,
    tags: [],
    status: 'available'
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = async (row: Dish) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  
  // 填充表单数据
  form.value = {
    name: row.name,
    price: row.price,
    description: row.description || '',
    category: row.Category,
    image_url: row.ImageURL || '',
    stock: row.Stock,
    tags: Array.isArray(row.Tags) ? row.Tags : JSON.parse(row.Tags || '[]'),
    status: row.Status || 'available'
  }
  
  // 保存当前编辑的菜品ID
  currentDishId.value = row.ID
}

// 处理删除
const handleDelete = async (dish: Dish) => {
  try {
    await ElMessageBox.confirm('确定要删除该菜品吗？', '提示', {
      type: 'warning'
    })
    
    const response = await fetch(`http://localhost:8080/api/dishes/${dish.ID}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    
    if (response.ok) {
      ElMessage.success('删除成功')
      loadDishes()
    } else {
      const data = await response.json()
      ElMessage.error(data.error || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8080/api/dishes'
          : `http://localhost:8080/api/dishes/${currentDishId.value}`
        
        const method = dialogType.value === 'add' ? 'POST' : 'PUT'
        
        const response = await fetch(url, {
          method,
          headers: {
            'Authorization': `Bearer ${store.state.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: form.value.name,
            price: form.value.price,
            description: form.value.description,
            category: form.value.category,
            image_url: form.value.image_url,
            stock: form.value.stock,
            tags: form.value.tags,
            status: form.value.status
          })
        })
        
        if (response.ok) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          loadDishes()
          // 重置表单
          resetForm()
        } else {
          const data = await response.json()
          ElMessage.error(data.error || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error('Submit error:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 添加重置表单函数
const resetForm = () => {
  form.value = {
    name: '',
    price: 0,
    description: '',
    category: '',
    image_url: '',
    stock: 0,
    tags: [],
    status: 'available'
  }
  currentDishId.value = null
}

// 在关闭对话框时重置表单
const handleDialogClose = () => {
  resetForm()
}

// 处理图片上传
const handleUploadSuccess = (response: any) => {
  console.log('Upload success response:', response)
  if (response.url) {
    form.value.image_url = `http://localhost:8080${response.url}`  // 添加完整的URL前缀
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 添加上传失败处理
const handleUploadError = (error: any) => {
  console.error('Upload error:', error)
  ElMessage.error('图片上传失败')
}

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 搜索
const handleSearch = () => {
  loadDishes()
}

// 根据标签内容返回不同的类型
const getTagType = (tag: string) => {
  const cleanTag = tag.replace(/[.,，。、！!？?；;：:""'']/g, '').trim()
  const tagTypeMap: Record<string, string> = {
    '辣': 'danger',
    '酸': 'warning',
    '甜': 'success',
    '咸': 'info',
    '招牌': 'primary',
    '新品': ''
  }
  return tagTypeMap[cleanTag] || ''
}

// 添加标签文本美化函数
const getTagText = (tag: string) => {
  const cleanTag = tag.replace(/[.,，。、！!？?；;：:""'']/g, '').trim()
  return cleanTag
}

// 处理标签输入，清理标点符号
const handleTagInput = (tag: string) => {
  return tag.replace(/[.,，。、！!？?；;：:""'']/g, '').trim()
}

// 添加一个变量保存当前编辑的菜品ID
const currentDishId = ref<number | null>(null)

onMounted(() => {
  loadDishes()
})
</script>

<style scoped>
.dishes-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.dish-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.dish-uploader:hover {
  border-color: #409EFF;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag-item {
  padding: 0 8px;
  height: 22px;
  line-height: 20px;
  font-size: 12px;
  border-radius: 2px;
  margin: 0 !important;
}

/* 自定义标签颜色 */
:deep(.el-tag--plain.el-tag--danger) {
  background-color: #fff2f0;
  border-color: #ffccc7;
  color: #ff4d4f;
}

:deep(.el-tag--plain.el-tag--primary) {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

:deep(.el-tag--plain.el-tag--warning) {
  background-color: #fffbe6;
  border-color: #ffe58f;
  color: #faad14;
}

:deep(.el-tag--plain.el-tag--success) {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
}

:deep(.el-tag--plain.el-tag--info) {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

/* 移除标签的悬停效果 */
.tag-item:hover {
  transform: none;
}
</style> 